﻿using System;
using System.Diagnostics;

namespace GameFramework.Diagnostics
{
    /// <summary>
    /// This class is useful for measuring the duration of a piece of code.
    /// This is a useful class for measuring the performance of your game.
    /// </summary>
    public class CodeTimeCounter : IDisposable
    {
        /// <summary>
        /// The timer object.
        /// </summary>
        private readonly Stopwatch stopwatch;

        /// <summary>
        /// The message to show at the end.
        /// </summary>
        private readonly string message;

        /// <summary>
        /// Initializes a new instance of the <see cref="CodeTimeCounter"/> class.
        /// </summary>
        public CodeTimeCounter() : this("Time: {0} ms")
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CodeTimeCounter"/> class.
        /// </summary>
        /// <param name="message">
        /// The message to show. 
        /// Use the placeholder {0} where you want to see the number of milliseconds.
        /// </param>
        public CodeTimeCounter(string message)
        {
            this.message = message;

            stopwatch = new Stopwatch();
            stopwatch.Start();
        }

        /// <summary>
        /// When the object is disposed the result is shown in the output window.
        /// </summary>
        public void Dispose()
        {
            stopwatch.Stop();

            Debug.WriteLine(String.Format(message, stopwatch.Elapsed.TotalMilliseconds));
        }
    }
}
